<?php

class CryoBB_Match
{
	private $data;
	
	/**
	 * Constructor, takes array from preg_match(_all)
	 * 
	 * @param array $match Array match from preg_match
	 * @param int $offset Parent offset
	 */
	public function __construct($match, $offset)
	{
		$this->data['match']			= $match[0][0];
		$this->data['tag']				= strtolower($match[1][0]);
		$this->data['parameter']		= $match[3][0];
		$this->data['parameterLength']	= strlen($match[3][0]);
		$this->data['content']			= $match[5][0];
		$this->data['offset']			= $match[0][1] + $offset;
		$this->data['length']			= strlen($this->match);
		$this->data['ignore']			= false;
	}
	
	/**
	 * Set ignore flag
	 * 
	 * @param bool $ignore
	 */
	public function setIgnore($ignore)
	{
		$this->data['ignore'] = $ignore;
		return $this;
	}
	
	/**
	 * Add number to offset.  Called from base as tags are evaluated
	 * 
	 * @param int $offset
	 */
	public function addOffset($offset)
	{
		$this->data['offset'] += $offset;
		return $this;
	}
	
	/**
	 * Calculate the difference in length of opening tag for inner offset
	 * 
	 * @param string $openTag
	 */
	public function calculateOpenTagDifference($openTag)
	{
		return strlen($openTag)
			- (
				strlen($this->tag)
				+ ($this->parameter ? $this->parameterLength + 1 : 0)
				+ 2
		);
	}
	
	public function childOffset()
	{
		return $this->offset + strlen($this->tag) + ($this->parameter ? strlen($this->parameter) + 1 : 0) + 2;
	}
	
	/**
	 * Check if match is in another match
	 * 
	 * @param CryoBB_Match $otherMatch
	 */
	public function inMatch($otherMatch) {
		return ($this->offset > $otherMatch->offset) && ($this->offset < ($otherMatch->offset + $otherMatch->length));
	}
	
	/**
	 * Process content with processor object
	 * 
	 * @param CryoBB_Tag $tag
	 */
	public function processContent($tag)
	{
		$this->content = $tag->processorObject->processContent($this->content, $this->parameter);
	}
	
	/**
	 * Process parameter with processor object
	 * 
	 * @param CryoBB_Tag $tag
	 */
	public function processParameter($tag)
	{
		$this->parameter = $tag->processorObject->processParameter($this->parameter);
	}
	
	/**
	 * Process parameter with CryoBB
	 * 
	 * @param array $tags
	 */
	public function reparseParameter($tags)
	{
		$cryobb = new CryoBB_Base();
		$cryobb->addTags($tags);
		$this->parameter = $cryobb->make($this->parameter);
	}
	
	public function __get($variable)
	{
		return $this->data[$variable];
	}
}